#include "formleases.h"
#include "ui_formleases.h"
#include "dlgleaseedit.h"
#include "dlgstoplease.h"
#include "dlgexportlease.h"

FormLeases::FormLeases(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormLeases)
{
    ui->setupUi(this);
    mp_l_model = new LeasesModel(this);
    connect(ui->btn_stop_lease, SIGNAL(clicked()), this, SLOT(stop_lease()));
    connect(ui->btn_new_lease, SIGNAL(clicked()), this, SLOT(new_lease()));
    connect(ui->btn_del_lease, SIGNAL(clicked()), this, SLOT(del_lease()));
    connect(ui->btn_export_lease, SIGNAL(clicked()), this, SLOT(export_lease()));
    connect(ui->tableView, SIGNAL(activated(QModelIndex)), this, SLOT(edit_lease(QModelIndex)));
    connect(ui->btn_filter, SIGNAL(clicked()), this, SLOT(update_filter()));
    ui->chbox_use_date_filter->setChecked(false);
    on_chbox_use_date_filter_clicked(false);
    ui->show_filter->setChecked(false);
    ui->filter_frame->hide();
}

FormLeases::~FormLeases()
{
    delete ui;
}

void FormLeases::set_dbms(HousingDBMS *p_dbms)
{
    mp_dbms = p_dbms;
    mp_l_model = dynamic_cast<ModelContainer *>(mp_dbms->get_models())->get_leases_model();
}


void FormLeases::update_model(const LeasesModel::Filter *p_filter)
{
        ui->tableView->setModel(NULL);
        mp_l_model->load_data(p_filter);
        ui->tableView->setModel(mp_l_model);
        mp_l_selection_model = ui->tableView->selectionModel();
        restore_selection();
        connect(mp_l_selection_model, SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(selection_changed(QModelIndex)));
        resize_table();
}


void FormLeases::new_lease()
{

    SLEE_HDB_REC qh_data;
    DlgLeaseEdit *p_le = new DlgLeaseEdit();
    p_le->set_dbms(mp_dbms);
    p_le->set_settings(mp_settings);
    p_le->set_data(SLEE_HDB_REC());
    if(p_le->exec())
    {
        if(p_le->is_changed())
        {
            qh_data = p_le->get_data();
            mp_dbms->db_put(LAKDB_LEASES, qh_data);
            update_model();
            lakhMsg()<<RUSTR("Новый договор внесен в БД!");
        }
    }

    delete p_le;
}


void FormLeases::del_lease()
{
    if(mqv_current_lease_index.isNull()) return;
    if(!mp_dbms->can_remove(LAKDB_LEASES, mqv_current_lease_index)) return;
    SLEE_HDB_REC qh_data = mp_dbms->get_data(LAKDB_LEASES, mqv_current_lease_index);
    mp_dbms->get_db(LAKDB_LEASES)->removeData(qh_data, mqv_current_lease_index);
    mqv_current_lease_index = QVariant();
    update_model();
    lakhMsg()<<RUSTR("Договор удален из БД.");
}

void FormLeases::edit_lease(const QModelIndex &mod_index)
{
    QVariant qv_index = mp_l_model->get_db_index(mod_index);
    SLEE_HDB_REC qh_data = mp_dbms->get_data(LAKDB_LEASES,  qv_index);

    QStringList qsl_bad_ids;
    QVariant qv_ap_index = qh_data.value(FLD_LS_AINDEX);
    QStringList qsl_ls_sps = qh_data.value(FLD_LS_SPSLST).toStringList();
    mp_dbms->get_apartment_lspace(qv_ap_index,qsl_ls_sps, &qsl_bad_ids);
    if(qsl_bad_ids.size())
    {
        lakhMsgE()<<RUSTR(" В договоре обнаружены несуществующие жил.площади. Они будут удалены при сохранении договора в БД.");
        foreach(QString qstr, qsl_bad_ids)
        {
            int indx = qsl_ls_sps.indexOf(qstr);
            if(indx < 0) continue;
            qsl_ls_sps.removeAt(indx);
        }
        qh_data[FLD_LS_SPSLST] = QVariant(qsl_ls_sps);
    }

    DlgLeaseEdit *p_le = new DlgLeaseEdit();
    p_le->set_dbms(mp_dbms);
    p_le->set_settings(mp_settings);
    p_le->set_data(qh_data);
    p_le->disable_num_check();
    if(p_le->exec())
    {
        if(p_le->is_changed())
        {
            qh_data = p_le->get_data();

            mp_dbms->db_put(LAKDB_LEASES, qh_data, qv_index);
            mp_l_model->update_data(mod_index);
            ui->tableView->setVisible(false);
            ui->tableView->setVisible(true);
            lakhMsg()<<RUSTR("Данные по договору обновлены!");
        }
    }
   delete p_le;
}


void FormLeases::selection_changed(const QModelIndex &mod_index)
{
     mqv_current_lease_index = mp_l_model->get_db_index(mod_index);
}


void FormLeases::restore_selection()
{
    QModelIndex mod_index = mp_l_model->get_mod_index(mqv_current_lease_index);
    mp_l_selection_model->select(mod_index, QItemSelectionModel::Select );
}

void FormLeases::on_show_filter_clicked(bool checked)
{
    if(!checked)
    {
        ui->filter_frame->hide();
        reset_filter();
    }

    if(checked) ui->filter_frame->show();
}

void FormLeases::update_filter()
{
    LeasesModel::Filter filter;
    filter.mqstr_street = ui->ledit_street->text().toUpper().trimmed();
    filter.mqstr_house = ui->ledit_house->text().toUpper().trimmed();
    filter.mqstr_ap_num =ui->ledit_ap_num->text();
    filter.mqstr_ten_fam = ui->ledit_tenfam->text().toUpper().trimmed();
    if(ui->dedit_s->isEnabled())
        filter.mqd_s = ui->dedit_s->date();
    else
        filter.mqd_s = QDate();
    if(ui->dedit_e->isEnabled())
        filter.mqd_e = ui->dedit_e->date();
    else
        filter.mqd_e = QDate();
    filter.m_before_s = ! ui->combo_sdate_dir->currentIndex();
    filter.m_before_e = ! ui->combo_edate_dir->currentIndex();
    update_model(&filter);
}

void FormLeases::reset_filter()
{
    update_model();
}

void FormLeases::on_chbox_use_date_filter_clicked(bool checked)
{
    if(checked)
    {
        ui->dedit_e->setEnabled(true);
        ui->dedit_s->setEnabled(true);
        ui->combo_edate_dir->setEnabled(true);
        ui->combo_sdate_dir->setEnabled(true);
    }
    else
    {
        ui->dedit_e->setEnabled(false);
        ui->dedit_s->setEnabled(false);
        ui->combo_edate_dir->setEnabled(false);
        ui->combo_sdate_dir->setEnabled(false);
    }
}


void FormLeases::stop_lease()
{
    if(mqv_current_lease_index.isNull())
    {
        lakhMsgE()<<RUSTR("Ошибка. Не выбран договор.");
        return;
    }
    SLEE_HDB_REC qh_data = mp_dbms->get_data(LAKDB_LEASES, mqv_current_lease_index);
    DlgStopLease *p_sl = new DlgStopLease();
    p_sl->set_dbms(mp_dbms);
    p_sl->set_data(qh_data);
    if(p_sl->exec())
    {
        qh_data = p_sl->get_data();
        mp_dbms->db_put(LAKDB_LEASES, qh_data, mqv_current_lease_index);
        lakhMsg()<<RUSTR("Данные по договору обновлены!");
    }
    delete p_sl;
}

void FormLeases::resizeEvent(QResizeEvent *p_ev)
{
    resize_table();
    return QWidget::resizeEvent(p_ev);
}

void FormLeases::resize_table()
{
    int x = ui->tableView->size().width();
    //0 - number            5
    //1 - start-date         10
    //2 - apartment         30
    //3 - tenant              15
    //4 - space              10
    //5 - stop-reason      10
    //6 - comments        20
    ui->tableView->setColumnWidth(0, x/20);
    ui->tableView->setColumnWidth(1, x/10);
    ui->tableView->setColumnWidth(2, x*30/100);
    ui->tableView->setColumnWidth(3, x*15/100);
    ui->tableView->setColumnWidth(4, x/10);
    ui->tableView->setColumnWidth(5, x/10);
    ui->tableView->setColumnWidth(6, x/5);
}

void FormLeases::export_lease()
{
    if(mqv_current_lease_index.isNull())
    {
        lakhMsgE()<<RUSTR("Ошибка. Не выбран договор.");
        return;
    }
   SLEE_HDB_REC qh_data = mp_dbms->get_data(LAKDB_LEASES, mqv_current_lease_index);
    DlgSettings dlgs;
    DlgExportLease *p_el = new DlgExportLease(mp_dbms, mp_settings);
    p_el->exec(qh_data);
    delete p_el;
}
